// (C) Copyright 2009, 2010 Communications Programming, Inc.
/***************************************************************************************************************
*  Name: Rfinder_TS601P01.c
*
*  Description: Finds the range of an object using an ultrasonic range finder model TS601P01
*
*  Calling Parameters:
*  
*	INT16 Read_Rfinder_TS601P01(IoPortId port, INT32 bit)
*
*	Returns > Distance in cms
*
*  Revision History:
*  Date    Who  Comments
*  ------  ---  -----------------------------------------------------------------------------------------
*  120430  PLM	Created.
***************************************************************************************************************/

#include <stdlib.h>
#include <plib.h>
#include <userLib.h>

INT16 Read_Rfinder_TS601P01(IoPortId port, INT32 bit)
{	
	int counter; // timing loop counter
	int sigin;
 
	counter = 0;	
	PORTSetPinsDigitalOut (port, bit);
	PORTSetBits (port, bit);
	delayT1_us(10);
	PORTClearBits (port, bit);
	delayT1_us(100);
	PORTSetPinsDigitalIn (port, bit); 
	sigin = PORTReadBits (port, bit);
	while(sigin == 0)
	{
		sigin = PORTReadBits (port, bit);
	}
	while(sigin != 0)
	{
		
		sigin = PORTReadBits (port, bit);
		delayT1_us(58);
		++counter;
	}
		
	delayT1_ms(1);
	return (counter);
}	
